package com.sunsheng.modules.juc;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) throws InterruptedException {
        //信号灯
        //Semaphore参数，表示最大支持线程数，初始许可大小为3
        Semaphore semaphore = new Semaphore(7);
        for (int i = 0; i <= 6; i++) {
            new Thread(() -> {
                try {
                    //请求获得许可，计数器减1
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + "====抢到了线程");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName() + "====离开了线程");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    //请求完成，释放许可，计数器加1
                    semaphore.release();
                }
            }, i + "").start();
        }
    }
}